package logic;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import org.apache.log4j.Logger;

import java.util.concurrent.ConcurrentHashMap;


public class PushThread implements Runnable {

    private NettyServer nettyServer = null;

    // 配置信息
    private final ConfigInfo configInfo = ConfigInfo.getInstance();
    // 日志对象
    private final static Logger logger = Logger.getLogger(NettyServerHandler.class);
    // 工具类对象
    private final Utils utils = new Utils();

    @Override
    public void run() {
        while (true) {
            try {
                ConcurrentHashMap<String, Channel> channelHashMap = ChannelMap.getChannelHashMap();
                if (channelHashMap != null && channelHashMap.size() > 0) {
                    for (String clientName : channelHashMap.keySet()) {
                        Channel channel = channelHashMap.get(clientName);
                        // 判断是否活跃
                        if (channel == null || !channel.isActive()) {
                            ChannelMap.removeChannelByName(clientName);
                            logger.warn(clientName + "已经断开连接");
                            continue;
                        }

                        if (configInfo.encoderStyle == 1) {
                            logger.info("推送数据(Byte[]=>" + clientName + ")：" + configInfo.pushMessage);
                            // 字节数组传输
                            byte[] sByte = utils.hexStringToBytes(configInfo.pushMessage);
                            ByteBuf byteBuf = Unpooled.wrappedBuffer(sByte);
                            // 发送消息
                            channel.writeAndFlush(byteBuf);
                        } else {
                            logger.info("推送数据(String=>" + clientName + ")：" + configInfo.pushMessage);
                            // 发送字符串消息
                            channel.writeAndFlush(configInfo.pushMessage);
                        }
                    }
                }
            } catch (Exception e) {
                logger.warn("推送数据发生异常！");
            } finally {
                try {
                    Thread.sleep(configInfo.pushInterval);
                } catch (Exception e) {

                }
            }
        }
    }
}